#!/usr/bin/env ruby

# A renderer to output logger notification elements in CSV format.
class RedBook::CsvRenderer < RedBook::Renderer
	
	# Render any logger notification element except +separator+ and +success+.	
	def render(element, options={})
		raise RendererError, "Invalid Element" unless element.xhash?
		rendered_element = nil
		case element.name.to_s
		when 'activity' then
			@output << activity(element, options)
		when 'tag','tags','tagset' then;
		when /^separator|success$/ then;
		else
			@output << render_simple_element(element, options) unless element.name == :command
			unless element.children.blank?
				render_children(element, options)
			end
		end
	end
	
	protected
	
	def render_simple_element(element, options={}) #:nodoc:
		[element.name.to_s.titleize, element.value.to_s.encode_out]
	end
	
	# Render a logger activity element.
	def activity(element, options={})
		# Type | Value | Message | Start Date | End Date | Duration | Tags #
		tags = element/:tag
		tags = !tags.blank? ? render_tags(tags) : nil
		start_date = (element/:start_time).first.value.strftime(RedBook::Config.instance.data[:time_format])
		end_date = !(element/:end_time).blank? ? (element/:end_time).first.value.strftime(RedBook::Config.instance.data[:time_format]) : nil
		time_unit = ''
		if RedBook::Config.instance.data[:csv_duration_time_unit] then
			case RedBook::Config.instance.data[:csv_duration_time_unit]
			when 'seconds' then
				dividend = 1
			when 'minutes' then
				dividend = 60
			when 'hours' then
				dividend = 3600
			when 'days' then
				dividend = 3600*24
			when 'weeks' then
				dividend = 3600*24*7
			when 'months' then
				dividend = 3600*24*30
			when 'years' then
				dividend = 3600*24*365
			else
				dividend = 1
			end
		else
			dividend = 1
		end
		duration = !(element/:duration).blank? ? ((element/:duration).first.value.to_f/dividend) : nil
		[element.name.to_s.titleize, nil, element.attributes[:message], start_date, end_date, duration, tags]
	end
	
	private
	
	def render_tags(tags)
		result = []
		tags.each { |t| result << t.value }
		result.join(',')
	end
	

end

